package service

import (
	"bytes"
	"core/corestruct"
	"core/coreutil"
	"core/myerrors"
	"filesvr/api/fsimg/data"
	"filesvr/config"
	"filesvr/mongo"
	"go.mongodb.org/mongo-driver/bson"
	"golang.org/x/net/context"
	"strconv"
)

const (
	COLLName = "image"
	URLPrev  = "/fsimg"
)

type mainService struct {
}

// Save 保存文件
func (p *mainService) Save(m *mongo.File, filedata *[]byte, ctx *corestruct.HttpContext) (*data.ImgDto, error) {
	coll := coreutil.MongoUtil.Collection(COLLName)
	ContentType := coreutil.FileUtil.GetFileContentType(filedata)
	m.ContentType = ContentType

	if m.Size/1024/1024 > 12 {
		bucket := coreutil.GetGridfsBucket(COLLName)
		err := bucket.UploadFromStreamWithID(m.Id, m.Name, bytes.NewBuffer(*filedata))
		if err != nil {
			return nil, myerrors.NewByErr(err)
		}
		m.FileId = strconv.FormatInt(m.Id, 10)
	} else {
		m.Data = filedata
		m.FileId = ""

	}
	_, err := coll.InsertOne(context.TODO(), m)
	if err != nil {
		return nil, myerrors.NewByErr(err)
	}
	var r = &data.ImgDto{
		Id:          m.Id,
		Name:        m.Name,
		Memo:        m.Memo,
		Url:         config.Config.File.FixUrl + URLPrev + "/down?id=" + strconv.FormatInt(m.Id, 10),
		ContentType: m.ContentType,
	}
	return r, nil

}

// Get  获取数据
func (p *mainService) Get(id int64, ctx *corestruct.HttpContext) (*mongo.File, *[]byte, error) {
	var m = &mongo.File{}
	coll := coreutil.MongoUtil.Collection(COLLName)
	filter := bson.D{{"_id", id}}
	err := coll.FindOne(context.TODO(), filter).Decode(m)
	if err != nil {
		return nil, nil, myerrors.NewByCode(myerrors.ERROR_DATANOTEXIST)
	}
	if "" != m.FileId {
		bucket := coreutil.GetGridfsBucket(COLLName)
		fileBuffer := bytes.NewBuffer(nil)
		if _, err = bucket.DownloadToStream(m.FileId, fileBuffer); err != nil {
			return nil, nil, myerrors.NewByErr(err)
		}
	} else {
		return m, m.Data, nil
	}
	return nil, nil, nil
}

var (
	MainService = &mainService{}
)
